package org.remembrance.scheduling02.service.impl.rate2;

import org.remembrance.scheduling02.model.EmailAddress;
import org.remembrance.scheduling02.model.ErrorMessage;
import org.remembrance.scheduling02.service.SendEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @author remembrance
 * @version 1.0
 * @date 2022/2/16 13:45
 * @desc 邮件发送具体实现类
 */
@Service("Rate2SendEmailServiceImpl")
public class Rate2SendEmailServiceImpl implements SendEmailService {
    private static final Logger logger = LoggerFactory.getLogger(Rate2SendEmailServiceImpl.class);
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void sendEmails(EmailAddress emailAddress, ErrorMessage errorMessage)  {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            //邮件主题
            helper.setSubject(emailAddress.getEmailSubject());
            //发件人
            helper.setFrom(emailAddress.getSender());
            //收件人
            helper.setTo(emailAddress.getReceiver());

            String[] cc = (String[]) emailAddress.getCopiedPeople().toArray();
            //抄送
            helper.setCc(cc);
            helper.setSentDate(new Date());
            //配置邮件模板的信息
            Context context = new Context();
            context.setVariable("table",errorMessage.getTableName());
            context.setVariable("data_date",errorMessage.getDataDate().toString());
            context.setVariable("data_inst",errorMessage.getDataInst());
            context.setVariable("key",errorMessage.getRecordKey());
            context.setVariable("column",errorMessage.getVerifyColumn());
            context.setVariable("info",errorMessage.getVerifyInfo());
            String process = templateEngine.process("mail.html", context);
            helper.setText(process,true);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            logger.error("错误信息:{}",e);
        } catch (MailException e) {
            logger.error("错误信息:{}",e);
        }
    }



}
